#include "E_Pthread_Pool.h"
#include "iostream"
#include "stdio.h"
#include "string"
#include "TCP.h"
#include <fstream>

using namespace std;

class my_tast : public Task{
public:
	std::string str;
	my_tast(std::string st){
	this->str = st;	
	}
	int run(){
	if(str[0] == '1')
	cout<<"注册新用户:"<<&str[1]<<endl;
       else
	 cout<<"Recvive："<<str<<endl;
	}
};
//------------------------------

//--------------TCP-test---------------
class TCP_tast : public Task{
public:
	string id1,id2,id3;
	int *connfd = nullptr;
	TCP_tast (int *ptr){
	connfd = ptr;	
	}
	int run(){
	char buf[100];
	char sendData = '1';
	int ret;
         while(1){

	memset(buf, 0, sizeof(buf));
	ret = read(*connfd, buf, sizeof(buf));
	if(ret < 0 || ret == 0){
		puts("read eoor");
		break;
	}
	buf[ret-1] = 0;//不含\n
	write(*connfd, &sendData, 1);
    cout<<"UserData: "<<buf<<endl;
	
	ofstream fp("base.txt", ios::out|ios::app);
	string str_data(buf);
	fp << str_data;
	fp.close();
   
}
	close(*connfd);
	free(connfd);
	cout<<"APP TCP end"<<endl;;
//	close(sockfd);

		}
	};


void* startReceiveTCP(void*);

E_PThread_Pool thread_pool(50,10,200);

int main(){

	pthread_t id;
	pthread_create(&id, NULL, startReceiveTCP ,NULL);

/*
	my_tast *tast1 = new my_tast("--------------"); 
*/

	while(1);
/*	sleep(1);
	long i=20001;
while(--i){

	thread_pool.addTask(tast1);
	
}

	sleep(2);	
	std::cout<<"<<<<<<<<<<<<<<<<<<<<<<<"<<i<<std::endl;
	std::cout<<"runcout:"<<thread_pool.runcount<<std::endl;
*/
return 0;
}

void* startReceiveTCP(void*){  
//-------------socker()------------------
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0){
	printf("sockfd is error\n");
	return nullptr;
}else
	printf("sock....、\n");
struct sockaddr_in myaddr;
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons(75);
myaddr.sin_addr.s_addr = INADDR_ANY;
//--------------bind()----------------------
if(0>bind(sockfd, (struct sockaddr*)&myaddr, sizeof(myaddr))){
	printf("bind error..\n");
	return nullptr;
}
else
	printf("bind..........\n");
//-------------listen()--------------
if(0 > listen(sockfd, 8)){
	perror("listen error...\n");
	return nullptr;;
}
else{
	printf("listen.....\n");
}
//-------------accept---------------
while(1){
	int* connfd = (int*)malloc(sizeof(int));
	*connfd = accept(sockfd, NULL, NULL);
	if(connfd < 0){
		puts("accept error");
		return nullptr;;
	}
	else{
		puts("accept........");	
		TCP_tast* tcp_tast = new TCP_tast(connfd);
		thread_pool.addTask(tcp_tast);
      		}
	}

}  
